from django.db import models
from user.models import SysUser
import uuid
from datetime import datetime, timedelta
import json
from django.utils import timezone


class Meeting(models.Model):
    """会议模型"""
    STATUS_CHOICES = [
        ('scheduled', '已安排'),
        ('active', '进行中'),
        ('ended', '已结束'),
        ('cancelled', '已取消'),
    ]

    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    title = models.CharField(max_length=200, verbose_name='会议主题')  # meeting_topic
    description = models.TextField(blank=True, verbose_name='会议描述')
    host = models.ForeignKey(SysUser, on_delete=models.CASCADE, verbose_name='主持人')  # organizer_id
    meeting_id = models.CharField(max_length=20, unique=True, verbose_name='会议号')
    password = models.CharField(max_length=20, blank=True, verbose_name='会议密码')

    scheduled_time = models.DateTimeField(verbose_name='计划开始时间')  # start_time
    duration = models.IntegerField(default=60, verbose_name='计划时长（分钟）')
    scheduled_end_time = models.DateTimeField(null=True, blank=True, verbose_name='计划结束时间')  # end_time
    actual_start_time = models.DateTimeField(null=True, blank=True, verbose_name='实际开始时间')
    actual_end_time = models.DateTimeField(null=True, blank=True, verbose_name='实际结束时间')

    status = models.CharField(max_length=20, choices=STATUS_CHOICES, default='scheduled', verbose_name='会议状态')

    # 会议设置
    enable_recording = models.BooleanField(default=True, verbose_name='启用录音')
    enable_transcription = models.BooleanField(default=True, verbose_name='启用语音转文字')
    enable_ai_summary = models.BooleanField(default=True, verbose_name='启用AI总结')

    created_at = models.DateTimeField(auto_now_add=True, verbose_name='创建时间')
    updated_at = models.DateTimeField(auto_now=True, verbose_name='更新时间')

    class Meta:
        verbose_name = '会议'
        verbose_name_plural = '会议'
        ordering = ['-created_at']

    def __str__(self):
        return f'{self.title} ({self.meeting_id})'

    def get_join_url(self):
        """生成加入会议的URL"""
        return f'/meeting/join/{self.meeting_id}'

    def is_active(self):
        """判断会议是否正在进行"""
        return self.status == 'active'

    def can_join(self):
        """判断是否可以加入会议"""
        return self.status in ['scheduled', 'active']

    def can_start(self, user):
        """判断用户是否可以开始会议"""
        # 检查是否是主持人
        if self.host != user:
            return False, '只有主持人可以开始会议'

        # 检查是否已经有会议正在进行
        active_meetings = Meeting.objects.filter(host=user, status='active')
        if active_meetings.exists():
            return False, '您已有会议正在进行，请先结束当前会议'

        # 检查会议是否在允许的时间范围内开始
        now = timezone.now()
        scheduled_start_time = self.scheduled_time
        time_diff = (scheduled_start_time - now).total_seconds()

        # 如果会议已经开始超过5分钟，则不允许开始
        if time_diff < -300:  # -300秒 = -5分钟
            return False, '会议已过开始时间5分钟以上，无法开始会议'

        # 如果会议开始时间还未到5分钟内，则不允许开始
        if time_diff > 300:  # 300秒 = 5分钟
            scheduled_time_str = scheduled_start_time.strftime("%Y-%m-%d %H:%M")
            return False, f'会议只能在计划开始时间（{scheduled_time_str}）前5分钟内开始'

        return True, '可以开始会议'


class MeetingTranscript(models.Model):
    """会议转写模型"""
    meeting = models.ForeignKey(Meeting, on_delete=models.CASCADE, related_name='transcripts')
    speaker_name = models.CharField(max_length=100, verbose_name='说话人')

    text = models.TextField(verbose_name='转写文字')
    confidence = models.FloatField(default=0.0, verbose_name='置信度')

    start_time = models.DateTimeField(verbose_name='开始时间')
    end_time = models.DateTimeField(verbose_name='结束时间')
    duration = models.FloatField(verbose_name='时长（秒）')

    # 音频文件信息
    audio_file = models.FileField(upload_to='meeting_audio/', null=True, blank=True, verbose_name='音频文件')
    audio_format = models.CharField(max_length=10, default='wav', verbose_name='音频格式')

    created_at = models.DateTimeField(auto_now_add=True)

    class Meta:
        verbose_name = '会议转写'
        verbose_name_plural = '会议转写'
        ordering = ['start_time']

    def __str__(self):
        return f'{self.speaker_name}: {self.text[:50]}...'


class MeetingSummary(models.Model):
    """会议总结模型"""
    meeting = models.OneToOneField(Meeting, on_delete=models.CASCADE, related_name='summary')

    # AI生成的总结
    summary_text = models.TextField(verbose_name='AI总结')
    key_points = models.JSONField(default=list, verbose_name='关键要点')
    action_items = models.JSONField(default=list, verbose_name='行动项')

    # 统计信息
    total_words = models.IntegerField(default=0, verbose_name='总字数')
    total_duration = models.IntegerField(default=0, verbose_name='总时长（秒）')

    # 生成信息
    generated_by = models.CharField(max_length=50, default='coze', verbose_name='生成工具')
    generated_at = models.DateTimeField(auto_now_add=True, verbose_name='生成时间')

    # 新增字段
    summary_file_path = models.CharField(max_length=500, blank=True, null=True, verbose_name='总结文件路径')

    class Meta:
        verbose_name = '会议总结'
        verbose_name_plural = '会议总结'

    def __str__(self):
        return f'{self.meeting.title} - 总结'

    def get_summary_data(self):
        """获取格式化的总结数据"""
        import re

        # 清理总结内容，移除多余的标记
        clean_summary = self.summary_text
        if clean_summary:
            # 移除Markdown标题标记（包括多级标题）
            clean_summary = re.sub(r'^#{1,6}\s*', '', clean_summary, flags=re.MULTILINE)
            # 移除粗体标记
            clean_summary = re.sub(r'\*\*(.*?)\*\*', r'\1', clean_summary)
            # 移除斜体标记
            clean_summary = re.sub(r'\*(.*?)\*', r'\1', clean_summary)
            # 移除多余的星号
            clean_summary = re.sub(r'\*+', '', clean_summary)
            # 移除行内代码标记
            clean_summary = re.sub(r'`+', '', clean_summary)

        # 将关键要点转换为列表格式，并清理内容
        clean_key_points = []
        if self.key_points:
            for point in self.key_points:
                if isinstance(point, str):
                    # 清理关键要点中的Markdown标记
                    clean_point = re.sub(r'^#{1,6}\s*', '', point)
                    clean_point = re.sub(r'\*\*(.*?)\*\*', r'\1', clean_point)
                    clean_point = re.sub(r'\*(.*?)\*', r'\1', clean_point)
                    clean_point = re.sub(r'\*+', '', clean_point)
                    clean_point = re.sub(r'`+', '', clean_point)
                    clean_key_points.append(clean_point.strip())
                else:
                    clean_key_points.append(point)

        # 处理summary_text可能包含JSON的情况
        try:
            # 尝试解析summary_text为JSON
            import json
            summary_data = json.loads(self.summary_text)
            # 如果是JSON格式且包含message字段，则使用该消息
            if 'message' in summary_data:
                clean_summary = summary_data['message']
                # 清理JSON中的内容
                clean_summary = re.sub(r'^#{1,6}\s*', '', clean_summary, flags=re.MULTILINE)
                clean_summary = re.sub(r'\*\*(.*?)\*\*', r'\1', clean_summary)
                clean_summary = re.sub(r'\*(.*?)\*', r'\1', clean_summary)
                clean_summary = re.sub(r'\*+', '', clean_summary)
                clean_summary = re.sub(r'`+', '', clean_summary)
        except:
            # 如果不是JSON格式，直接使用原文本并清理
            if self.summary_text:
                clean_summary = self.summary_text
                clean_summary = re.sub(r'^#{1,6}\s*', '', clean_summary, flags=re.MULTILINE)
                clean_summary = re.sub(r'\*\*(.*?)\*\*', r'\1', clean_summary)
                clean_summary = re.sub(r'\*(.*?)\*', r'\1', clean_summary)
                clean_summary = re.sub(r'\*+', '', clean_summary)
                clean_summary = re.sub(r'`+', '', clean_summary)

        return {
            'meeting_info': {
                'title': self.meeting.title,
                'description': self.meeting.description if self.meeting.description else '暂无',
                'date': self.meeting.actual_start_time.strftime(
                    '%Y-%m-%d %H:%M:%S') if self.meeting.actual_start_time else '',
                'duration': self.total_duration,
            },
            'summary': clean_summary.strip() if clean_summary else '',  # 使用清理后的总结
            'key_points': clean_key_points,  # 使用清理后的关键要点
            'key_points_markdown': "",  # 不再使用Markdown格式的关键要点
            'action_items': self.action_items,
        }


class OptimizedTranscript(models.Model):
    """优化后的转写记录模型"""
    meeting = models.ForeignKey(Meeting, on_delete=models.CASCADE, related_name='optimized_transcripts')
    speaker_name = models.CharField(max_length=100, verbose_name='说话人')

    # 原始和优化后的文字
    original_text = models.TextField(verbose_name='原始转写文字', blank=True)
    optimized_text = models.TextField(verbose_name='优化后文字')
    confidence = models.FloatField(default=0.0, verbose_name='置信度')

    # 时间信息
    start_time = models.DateTimeField(verbose_name='开始时间')
    processing_time = models.FloatField(default=0.0, verbose_name='处理时长（秒）')

    # Coze工作流信息
    workflow_id = models.CharField(max_length=100, blank=True, verbose_name='工作流ID')
    optimization_level = models.CharField(max_length=20, default='high', verbose_name='优化级别')

    created_at = models.DateTimeField(auto_now_add=True)

    class Meta:
        verbose_name = '优化转写记录'
        verbose_name_plural = '优化转写记录'
        ordering = ['start_time']

    def __str__(self):
        return f'{self.speaker_name}: {self.optimized_text[:50]}...'